/*
 * main.cpp
 *
 *  Created on: 10/09/2011
 *      Author: agustin
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <vector>
#include <dirent.h>
#include <sys/types.h>
using namespace std;

vector<string> readDirectory(const string& path = string()) {
	vector<string> result;
	dirent* dirEntry;
	DIR* dir;
	unsigned char isFile = 0x8;
	unsigned char isFolder = 0x4;

	//Abre el directorio
	dir = opendir(path.empty() ? "." : path.c_str());
	if (dir) {
		//Itera por el directorio
		while (true) {
			dirEntry = readdir(dir);
			if (dirEntry == NULL) {
				break;
			}
			/*Si es un archivo lo agrega al vector, si no se llama a la
			 funcion de forma recursiva*/
			if (dirEntry->d_type == isFile) {
				string filePath = path + dirEntry->d_name;
				result.push_back(filePath);
			} else if (dirEntry->d_type == isFolder) {
				string folder(dirEntry->d_name);
				if (folder != "." && folder != "..") {
					string recPath = path + dirEntry->d_name + "/";
					vector<string> files = readDirectory(recPath);
					for (size_t i = 0; i < files.size(); i++) {
						result.push_back(files[i]);
					}
				}
			}
		}
		closedir(dir);
	}
	return result;
}

int main(int argc, char **argv) {
	try {
		if (argc < 2) {
			exit(EXIT_FAILURE);
		}
		string op(argv[1]);
		string path;

		if (op == "-i") {
			if (argv[2] == NULL) {
				path = "";
			} else {
				path = string(argv[2]);
			}
		} else if (op == "-q") {
		} else {
			exit(EXIT_FAILURE);
		}

		vector<string> files = readDirectory(path);
		sort(files.begin(), files.end());

		//Test
		for (size_t i = 0; i < files.size(); i++) {
			cout << files[i] << endl;
		}

	} catch (exception& e) {
		cout << e.what() << endl;
	}
}
